﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using tuwien.auto.eibclient;
using KNXFramework.Logging;

namespace KNXFramework.KNXObjects.ValueObjects
{
    internal class DateObjectValue : IValueObject   
    {
        private DateTime m_Value = DateTime.MinValue;

        #region Constructors
        public DateObjectValue(string value)
        {
            if (value.ToLower() == "now")
            {
                m_Value = DateTime.Now;
                return;
            }

            if (!DateTime.TryParse(value, out m_Value))
                throw new ApplicationException("DateObjectValue, cannot parse input string. Val : " + value);

        }
        public DateObjectValue(EIBBuffer buffer)
        {
            if (buffer.data.Length < 5)
            {
                CustomLogger.WriteErrorEntry("DateObject : Invalid packed received (too short)");
            }
            byte[] buf = buffer.data;
            int day, month, year;
            day = buf[2];
            month = buf[3];
            year = buf[4];

            if (year >= 90)
                year += 1900;
            else
                year += 2000;

            m_Value = new DateTime(year, month, day);

        }
        public DateObjectValue()
        {
            m_Value = DateTime.Now;
        }
        #endregion
        
        public override string ToString()
        {
            return m_Value.ToString("yyyy-MM-dd");
        }

        #region IValueObject Members

        public void AdaptBufferBeforeSending(bool isWrite, tuwien.auto.eibclient.EIBBuffer buffer)
        {
            byte[] b = new byte[5];
            b[0] = buffer.data[0];
            b[1] = buffer.data[1];
            b[2] = (byte)m_Value.Day;
            b[3] = (byte)m_Value.Month;
            b[4] = (byte)(m_Value.Year < 2000 ? m_Value.Year - 1900 : m_Value.Year - 2000);
            buffer.data = b;
        }

        #endregion

        #region IEquatable<IValueObject> Members

        public bool Equals(IValueObject other)
        {
            DateObjectValue otherVal = other as DateObjectValue;
            bool equality = false;
            if (otherVal != null)
                equality = m_Value.Equals(otherVal.m_Value);
            return equality;
        }

        #endregion
    }
}
